from fastapi import APIRouter, UploadFile, File, HTTPException, Request
from fastapi.templating import Jinja2Templates
import os
from pathlib import Path
import uuid
from datetime import datetime
from config import BASE_URL, UPLOAD_DIR, MAX_SIZE_MB, ALLOWED_TYPES

# 创建路由
router = APIRouter()

# 模板配置
templates = Jinja2Templates(directory="static")

@router.get("/")
async def index(request: Request):
    return templates.TemplateResponse("index.html", {"request": request})

@router.get("/upload_image_url.html")
async def upload_page(request: Request):
    return templates.TemplateResponse("upload_image_url.html", {"request": request})

@router.get("/paddleocr281.html")
async def paddleocr_page(request: Request):
    return templates.TemplateResponse("paddleocr281.html", {"request": request})

@router.post("/upload_image")
async def upload_image(file: UploadFile = File(...)):
    # 验证文件类型
    if file.content_type not in ALLOWED_TYPES:
        raise HTTPException(400, detail=f"仅支持 {', '.join(ALLOWED_TYPES)} 格式")

    # 读取文件内容以获取文件大小
    content = await file.read()
    file_size = len(content)
    
    # 验证文件大小
    if file_size > MAX_SIZE_MB * 1024 * 1024:
        raise HTTPException(400, detail=f"文件超过{MAX_SIZE_MB}MB限制")

    # 生成按日期分类的存储路径
    date_path = datetime.now().strftime("%Y/%m")
    save_path = Path(UPLOAD_DIR) / date_path
    save_path.mkdir(parents=True, exist_ok=True)

    # 生成唯一文件名
    ext = os.path.splitext(file.filename)[1] if os.path.splitext(file.filename)[1] else ".jpg"
    filename = f"{uuid.uuid4().hex}{ext}"
    filepath = save_path / filename
    
    # 保存文件
    with open(filepath, "wb") as buffer:
        buffer.write(content)
    
    # 返回可访问URL
    image_url = f"{BASE_URL}/static/uploads/{date_path}/{filename}"
    return {
        "url": image_url,
        "filename": filename,
        "size": file_size
    }

@router.post("/upload_file")
async def upload_file(file: UploadFile = File(...)):
    # 文件大小限制为100MB
    MAX_FILE_SIZE_MB = 100
    
    # 读取文件内容以获取文件大小
    content = await file.read()
    file_size = len(content)
    
    # 验证文件大小
    if file_size > MAX_FILE_SIZE_MB * 1024 * 1024:
        raise HTTPException(400, detail=f"文件超过{MAX_FILE_SIZE_MB}MB限制")

    # 生成按日期分类的存储路径
    date_path = datetime.now().strftime("%Y/%m")
    save_path = Path(UPLOAD_DIR) / date_path
    save_path.mkdir(parents=True, exist_ok=True)

    # 生成唯一文件名，保留原始扩展名
    ext = os.path.splitext(file.filename)[1] if os.path.splitext(file.filename)[1] else ""
    filename = f"{uuid.uuid4().hex}{ext}"
    filepath = save_path / filename
    
    # 保存文件
    with open(filepath, "wb") as buffer:
        buffer.write(content)
    
    # 返回可访问URL
    file_url = f"{BASE_URL}/static/uploads/{date_path}/{filename}"
    return {
        "url": file_url,
        "filename": filename,
        "original_filename": file.filename,
        "size": file_size
    } 